<template>
  <div class="question_analysis_container">
    <div class="search_box">
      <div @click="exportQsAnalysis" class="btn btn_add">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">导出</span>
      </div>

      <div class="btn btn_search fr" @click="searchQsAnalysis(searchFormQsAnalysis)">
        <span class="btn_txt">查询</span>
      </div>

      <div class="fr">
        <el-form :model="searchFormQsAnalysis" :inline="true" class="searchFormQsAnalysis">
          <el-form-item size="small">
            <el-select @change="changeQuestion" clearable style="width:300px;" value-key="questionId" v-model="searchFormQsAnalysis.question" placeholder="请选择题目">
              <el-option v-for="(item, index) in questionList" :key="item.questionId" :label="`${index+1}、${item.questionContent}`" :value="item">
              </el-option>
            </el-select>
          </el-form-item> 
          <el-form-item size="small">
            <el-select @change="changeSchool" clearable style="width:200px;" multiple collapse-tags v-model="searchFormQsAnalysis.schoolId" placeholder="请选择校区">
              <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" v-if="questionType == 'listenToTheClass'">
            <el-date-picker
              style="width:230px;"
              v-model="searchFormQsAnalysis.financialMonth"
              type="daterange"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <div v-if="questionType == 'midTerm'" style="display: inline-block;">
            <el-form-item size="small">
              <el-date-picker
                style="width:130px;"
                value-format="yyyy"
                format="yyyy年"
                v-model="searchFormQsAnalysis.financialYear"
                type="year"
                placeholder="学年">
              </el-date-picker>
            </el-form-item>

            <el-form-item size="small">
              <el-date-picker
                style="width:90px;"
                value-format="MM"
                format="M月"
                @change="changeMonth"
                v-model="searchFormQsAnalysis.financialMonth"
                type="month"
                placeholder="月份">
              </el-date-picker>
            </el-form-item>
          </div>

          
        </el-form>
      </div>
      
      <div class="clear"></div>
    </div>

    <div class="content_box">
      <div class="top">
        <div class="left content_item">
          <div class="title">
            <span class="fl">问题描述 : {{questionRemark}}</span>
            <span class="fr">指标 : {{operationalIndicators}}</span>
            <div class="clear"></div>
          </div>
          <div class="table_box">
            <adminTable :tableHead="tableHeadLeft" :tableData="tableDataLeft" ></adminTable>
            <el-pagination
              class="pagination"
              @size-change="handleSizeChangeLeft"
              @current-change="handleCurrentChangeLeft"
              :current-page="pageLeft.curPage"
              :page-sizes="[5, 20, 50]"
              :page-size="pageLeft.pageSize"
              layout="total, prev, pager, next, jumper"
              :total="pageLeft.totalRows">
            </el-pagination>
          </div>
        </div>
        <div class="right content_item" id="echarts"></div>
      </div>

      <div class="bottom content_item">
        <div class="title">
          <span class="">文字信息</span>
        </div>
        <adminTable :tableHead="tableHeadBottom" :tableData="tableDataBottom" ></adminTable>
        <el-pagination
          class="pagination"
          @size-change="handleSizeChangeBottom"
          @current-change="handleCurrentChangeBottom"
          :current-page="pageBottom.curPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageBottom.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageBottom.totalRows">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<style>
  .question_analysis_container .left .el-table th,
  .question_analysis_container .left .el-table td {
    padding: 3px 0 !important;
  }

  .question_analysis_container .left .pagination {
    padding: 5px 20px !important; 
  }
</style>
<style scoped>
.content_box {
  padding: 0 15px 15px;
  box-sizing: border-box;
  width: 100%;
}
.content_box .content_item {
  box-shadow:1px 1px 4px 2px rgba(213,212,212,0.5);
  border-radius:8px;
}
.content_box .top {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 15px;
}
.content_box .top .left {
  width: 60%;
  margin-right: 15px;
  min-height: 270px;
}
.content_box .top .right {
  width: 40%;
  height: 270px;
}
.content_box .bottom{
  min-height: 260px;
  width: 100%;
}

.content_box .title{
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  box-sizing: border-box;
}
.content_box .title span {
  color: #77A4FF;
  font-size: 12px;
  letter-spacing: 1.5px;
}
.search_box {
  padding: 0 15px;
  box-sizing: border-box;
}

.btn_search{
  padding: 0 20px;
  text-align: center;
  height: 32px;
  font-size: 12px;
  background: #FBA56C;
  line-height: 32px;
}

</style>


<script>

import adminTable from '@/components/assembly/adminTable'
import {
  createNamespacedHelpers,
  mapState,
} from "vuex";
let {
  // mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("questionAnalysis");

let monthType = '';

// console.log(questionType)

export default {
  data() {
    return {
      jwtAuth: {},
      schoolList: [],
      /* ===== 逐题分析 ====== */
      questionList: [],
      questionRemark: '',
      operationalIndicators: '',
      searchFormQsAnalysis: {
        schoolId: [],
        financialMonth: null,
        question: {},
        questionId: '',
        rptTimeStart: '',
        rptTimeEnd: '',
      },
      tableHeadLeft: {
        border: true,
        data: [
          {
            name: "校区",
            key: "schoolName",
            align: "center",
          },
          {
            name: "评价数目",
            key: "evaluationNumber",
            align: "center",
            width: '50px',
          },
          {
            name: "1分",
            key: "onePoint",
            align: "center",
            width: '68px',
            progressBar: '#FFC8A3',
          },
          {
            name: "2分",
            key: "twoPoint",
            align: "center",
            width: '68px',
            progressBar: '#FFC8A3',
          },
          {
            name: "3分",
            key: "threePoint",
            align: "center",
            width: '68px',
            progressBar: '#FFC8A3',
          },
          {
            name: "4分",
            key: "fourPoint",
            align: "center",
            width: '68px',
            progressBar: '#FFC8A3',
          },
          {
            name: "5分",
            key: "fivePoint",
            align: "center",
            width: '68px',
            progressBar: '#FFC8A3',
          },
          {
            name: "本月平均分",
            key: "averageScore",
            align: "center",
            width: '60px',
          },
        ]
      },
      tableDataLeft: [],
      pageLeft: {
        curPage: 1,
        pageSize: 5,
        totalRows: 0,
      },

      tableHeadBottom: {
        data: [
          {
            name: "校区",
            key: "schoolName",
            align: "center",
            width: '120px'
          },
          {
            name: "题目",
            key: "questionContent",
            align: "center",
            // width: '250px'
          },
          {
            name: "评语",
            key: "textData",
            align: "center"
          },
        ]
      },
      tableDataBottom: [],
      pageBottom: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      questionnaireType: '',
      /* ===== 逐题分析 END ====== */
    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));


    /**
     * listenToTheClass : 试听课程  1
     * noRegistration :   不报名    2  
     * signUp :           报名      3        
     * midTerm :          期中月    4      
    */
    switch (this.questionType) {
      case 'listenToTheClass':
        this.questionnaireType = '1'
        this.searchFormQsAnalysis.financialMonth = [];
        break;
      // case 'noRegistration':
      //   this.questionnaireType == '2'
      //   break;
      // case 'signUp':
      //   this.questionnaireType == '3'
      //   break;
      case 'midTerm':
        this.questionnaireType = '4'
        this.searchFormQsAnalysis.financialMonth = '';
        break;
    
      default:
        break;
    }

    this.queryAllQuestion(this.questionType);
  },
  watch: {
    isActiveEcharts(newVal, oldVal) {
      if(this.isActiveEcharts) {
        setTimeout(() => {
          this.initLeftData(this.searchFormQsAnalysis);
          this.initBottomData(this.searchFormQsAnalysis);
          this.initEchartsData();
        }, 0)
      }
    }
  },
  mounted() {
    this.queryAllSchool();
  },
  methods: {
    ...mapActions([
      "formGet",
      "post",
      "export",
    ]),

    exportQsAnalysis() {
      let data = {};
      data.questionId = this.searchFormQsAnalysis.question.questionId || ''
      data.rptTimeStart = this.searchFormQsAnalysis.financialMonth[0] || ''
      data.rptTimeEnd = this.searchFormQsAnalysis.financialMonth[1] || ''
      data.questionnaireType = this.questionnaireType

      // data.schoolId = this.searchFormQsAnalysis.schoolId

      let schoolIdArr = [];
      data.schoolId = this.searchFormQsAnalysis.schoolId
      console.log(data.schoolId)
      if(!data.schoolId || data.schoolId.length == 0) {
        this.schoolList.forEach(item => {
          schoolIdArr.push(item.schoolId);
        })
        data.schoolId = schoolIdArr;
      }else{
        data.schoolId = this.searchFormQsAnalysis.schoolId
      }

      // data.curPage = ''
      // data.pageSize = ''

      this.exportLeft(data);


      setTimeout(() => {
        this.exportRight(data)
      }, 1000)

      setTimeout(() => {
        this.exportBottom(data)
      }, 2000)
      

      
      
    },

    exportLeft(data) {
      this.export({
        API: 'exportBmExamplesPageListForQuestion',
        data: data
      }).then(res => {
        
      }).catch(err => {

      })
    },
    exportRight(data) {
      console.log('aaaa')
      this.export({
        API: 'exportBmExamplesAverageHistory',
        data: data
      }).then(res => {
        
      }).catch(err => {

      })
    },
    exportBottom(data) {
      this.export({
        API: 'exportBmExamplesTextData',
        data: data
      }).then(res => {

      }).catch(err => {

      })

    },

    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId

      // let schoolIds = null
      // let arr = this.jwtAuth.schoolId.split(',')
      // console.log(arr);
      // for(let i=0; i<arr.length; i++) {
      //   if(arr[i] == '') {
      //     schoolIds = [];
      //     break;
      //   }else{
      //     schoolIds = this.jwtAuth.schoolId.split(',')
      //   }
      // }

      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        // if(btnId) {
        //   this.powerSchoolList = res
        //   this.formDataMonth.schoolId = this.powerSchoolList[0].schoolId
        //   if(this.activeName == 'monthly') {
        //     this.changeMonthSchool(this.formDataMonth.schoolId)
        //   }
          
        // }else{
        //   this.schoolList = res
        // }
        this.schoolList = res;
        this.schoolList = this.schoolList.filter(val => {
          return val.schoolId !== '';
        });

        this.initLeftData(this.searchFormQsAnalysis);
        this.initBottomData(this.searchFormQsAnalysis);
        this.initEchartsData();
        // this.powerSchoolList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    queryAllQuestion(type) {
      this.formGet({
        API: 'queryQuestionByQuestionnaireType',
        data: {
          questionnaireType: type
        }
      }).then(res => {
        this.questionList = res.list
      }).catch(err => {
        this.$message.error(err);
      })
    },

  /* ========================= 逐题分析START =========================== */
    changeQuestion(e) {
      console.log(e);
      this.questionRemark = e.questionContent;
      /**
       * 教学/运营/招生
       */
      switch (e.operationalIndicators) {
        case '0':
          this.operationalIndicators = '无'
          break;
        case '1':
          this.operationalIndicators = '教学'
          break;
        case '2':
          this.operationalIndicators = '运营'
          break;
        case '3':
          this.operationalIndicators = '招生'
          break;
      
        default:
          break;
      }

      this.initLeftData(this.searchFormQsAnalysis);
      this.initEchartsData();
      this.initBottomData(this.searchFormQsAnalysis);

    },

    changeSchool(e) {
    },

    searchQsAnalysis(searchFormSchoolAnalysis) {
      this.pageLeft.curPage = 1;
      this.pageBottom.curPage = 1;
      
      console.log('asdasdasd')

      this.initLeftData(this.searchFormQsAnalysis);
      this.initEchartsData();
      this.initBottomData(this.searchFormQsAnalysis);
    },

    /* =========== initData START============ */
    initLeftData(searchForm) {
      let searchValue = searchForm || this.searchFormQsAnalysis || '';
      let data = {}
      Object.assign(data, searchValue);
      data.curPage = this.pageLeft.curPage;
      data.pageSize = this.pageLeft.pageSize;
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;

      let schoolIdArr = [];
      console.log(this.schoolList)
      if(!data.schoolId || data.schoolId.length == 0) {
        this.schoolList.forEach(item => {
          schoolIdArr.push(item.schoolId);
        })
        data.schoolId = schoolIdArr;
      }else{
        data.schoolId = this.searchFormQsAnalysis.schoolId
      }


      // if(this.searchFormQsAnalysis.financialMonth) {
      //   data.rptTimeStart = this.searchFormQsAnalysis.financialMonth[0];
      //   data.rptTimeEnd = this.searchFormQsAnalysis.financialMonth[1];
      // }

      if(this.questionnaireType == '4') {
        
        let nowYear = new Date().getFullYear();
        let nowMonth = new Date().getMonth() + 1;

        let lastDayNum = new Date(data.financialYear || nowYear, data.financialMonth || nowMonth, 0).getDate()

        if(data.financialYear && data.financialMonth) { //  有年 有月
          data.rptTimeStart = `${data.financialYear}-${data.financialMonth}-01 00:00:00`
          data.rptTimeEnd = `${data.financialYear}-${data.financialMonth}-${lastDayNum} 23:59:59`
        } else if (data.financialYear && !data.financialMonth) {  // 有年 无月
          data.rptTimeStart = `${data.financialYear}-09-01 00:00:00`
          data.rptTimeEnd = `${Number(data.financialYear) + 1}-08-${lastDayNum} 23:59:59`
        } else{   // 无年 无月
          data.rptTimeStart = ''
          data.rptTimeEnd = ''
        }

        
      }else{
        if(this.searchFormQsAnalysis.financialMonth) {
          data.rptTimeStart = this.searchFormQsAnalysis.financialMonth[0];
          data.rptTimeEnd = this.searchFormQsAnalysis.financialMonth[1];
        }

      }

      data.questionId = this.searchFormQsAnalysis.question.questionId;
      // data.schoolId = this.searchFormQsAnalysis.schoolId;

      data.questionnaireType = this.questionnaireType

      console.log(data);
      // return false;

      this.post({
        API: 'queryBmExamplesPageListForQuestion',
        data: data
      }).then(res => {
        this.tableDataLeft = res.data;
        if(this.searchFormQsAnalysis.question.questionType == 3) {
          this.tableDataLeft.forEach(item => {
            console.log(item)
            item.onePoint = '/';
            item.twoPoint = '/';
            item.threePoint = '/';
            item.fourPoint = '/';
            item.fivePoint = '/';
            item.averageScore = '/';
          })
        }
        this.pageLeft = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    initEchartsData(bool) {
      let searchValue = this.searchFormQsAnalysis || '';
      let data = {}
      Object.assign(data, searchValue);
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;

      let schoolIdArr = [];
      if(!data.schoolId || data.schoolId.length == 0) {
        this.schoolList.forEach(item => {
          schoolIdArr.push(item.schoolId);
        })
        data.schoolId = schoolIdArr;
      }else{
        data.schoolId = this.searchFormQsAnalysis.schoolId
      }

      let nowYear = new Date().getFullYear();
      let nowMonth = new Date().getMonth() + 1;
      if(nowMonth < 9) {
        nowYear -= 1;
      }

      let year;
      if(data.financialYear) {
        year = Number(data.financialYear) + 1
      }else{
        year = nowYear + 1
      }

      if(data.financialYear && data.financialMonth) {
        console.log('aaa')
        if(data.financialMonth < 9) {
          year = data.financialYear
        }else{
          year = Number(data.financialYear) + 1
        }
      }

      if(this.questionnaireType == '4') {
        data.rptTimeStart = `${year - 1}-09-01 00:00:00`
        data.rptTimeEnd = `${year}-08-31 23:59:59`
      }else{
        data.rptTimeStart = this.searchFormQsAnalysis.financialMonth[0];
        data.rptTimeEnd = this.searchFormQsAnalysis.financialMonth[1];
      }

      // if(this.searchFormQsAnalysis.financialMonth) {
      //   if(this.questionnaireType == '4') {
      //     data.rptTimeStart = `${data.financialYear || nowYear}-09-01 00:00:00`
      //     data.rptTimeEnd = `${Number(data.financialYear)+1 || nowYear + 1}-08-31 23:59:59`
      //   }else{
      //     data.rptTimeStart = this.searchFormQsAnalysis.financialMonth[0];
      //     data.rptTimeEnd = this.searchFormQsAnalysis.financialMonth[1];
      //   }
      // }

      data.questionId = this.searchFormQsAnalysis.question.questionId;
      // data.schoolId = this.searchFormQsAnalysis.schoolId;

      data.questionnaireType = this.questionnaireType

      this.post({
        API: 'queryBmExamplesAverageHistory',
        data: data,
      }).then(res => {
        // console.log(res);
        this.initEcharts(res, true);
      }).catch(err => {
        this.$message.error(err);
      })
    },
    initBottomData(searchForm) {
      let searchValue = searchForm || this.searchFormQsAnalysis || '';
      let data = {}
      Object.assign(data, searchValue);
      data.curPage = this.pageBottom.curPage;
      data.pageSize = this.pageBottom.pageSize;
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;

      let schoolIdArr = [];
      if(!data.schoolId || data.schoolId.length == 0) {
        this.schoolList.forEach(item => {
          schoolIdArr.push(item.schoolId);
        })
        data.schoolId = schoolIdArr;
      }else{
        data.schoolId = this.searchFormQsAnalysis.schoolId
      }

      if(this.questionnaireType == '4') {
        
        let nowYear = new Date().getFullYear();
        let nowMonth = new Date().getMonth() + 1;

        let lastDayNum = new Date(data.financialYear || nowYear, data.financialMonth || nowMonth, 0).getDate()

        if(data.financialYear && data.financialMonth) { //  有年 有月
          data.rptTimeStart = `${data.financialYear}-${data.financialMonth}-01 00:00:00`
          data.rptTimeEnd = `${data.financialYear}-${data.financialMonth}-${lastDayNum} 23:59:59`
        } else if (data.financialYear && !data.financialMonth) {  // 有年 无月
          data.rptTimeStart = `${data.financialYear}-09-01 00:00:00`
          data.rptTimeEnd = `${Number(data.financialYear) + 1}-08-${lastDayNum} 23:59:59`
        } else{   // 无年 无月
          data.rptTimeStart = ''
          data.rptTimeEnd = ''
        }

        
      }else{
        if(this.searchFormQsAnalysis.financialMonth) {
          data.rptTimeStart = this.searchFormQsAnalysis.financialMonth[0];
          data.rptTimeEnd = this.searchFormQsAnalysis.financialMonth[1];
        }

      }

      

      

      
      



      data.questionId = this.searchFormQsAnalysis.question.questionId;
      // data.schoolId = this.searchFormQsAnalysis.schoolId;
      
      data.questionnaireType = this.questionnaireType

      this.post({
        API: 'queryBmExamplesTextData',
        data: data
      }).then(res => {
        this.tableDataBottom = res.data;
        this.pageBottom = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    /* =========== initData END ============ */


    initEcharts(data, bool) {
      let myChart = this.$echarts.init(document.getElementById("echarts"));

      let schoolNameArr = [];

      
      let option = {
        color: ["#FED976", "#A8CDED",  '#A1DAA4', '#A9C2F4', '#FC84A9', '#FFD1B3', ],
        grid: {
          bottom: '15%',
          right: '5%'
        },
        legend: {       // 图例
          data: schoolNameArr,
          icon: 'circle',
          top: '5%',
          textStyle: {
            color: "#485465",
            fontSize: 11,
            fontWeight: 400,
          },
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 35,
        },
        tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
            shadowStyle: {
              color: 'rgba(150,150,150,0.15)',
            } 
          }
        },
        xAxis: {
          type: 'category',
          data: ['8月', '9月', '10月', '11月','12月', '1月', '2月', '3月','4月', '5月', '6月', '7月', '8月'],
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {        // x轴 标签
            show: true,
            rotate: 45,
            textStyle: {
              color: "#485465",
              fontSize: 10,
              fontWeight: 400
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '得分',
          axisTick: {
            show: false
          },
          max: 5,
          min: 3.5,
          axisLine: {
            show: false
          },
          axisLabel: {        // x轴 标签
            show: true,
            textStyle: {
              color: "#485465",
              fontSize: 10,
              fontWeight: 400
            }
          }
        },
        series: [
        ]
      };

      
      console.log(data);
      if(data.length > 0) {
        data.forEach(item => {
          schoolNameArr.push(item.schoolName);
          let schoolData = [];
          schoolData.push(item.septemberData)
          schoolData.push(item.octoberData)
          schoolData.push(item.novemberData)
          schoolData.push(item.decemberData)
          schoolData.push(item.januaryData)
          schoolData.push(item.februaryData)
          schoolData.push(item.marchData)
          schoolData.push(item.aprilData)
          schoolData.push(item.mayData)
          schoolData.push(item.juneData)
          schoolData.push(item.julyData)
          schoolData.push(item.augustData)
          let obj = {
            name: item.schoolName,
            data: schoolData,
            type: 'line',
            smooth: 0.4,
          }

          option.series.push(obj)
        })
      }


      myChart.setOption(option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });

      if(bool) {
        setTimeout(() => {
          myChart.resize();
        }, 0)
      }
    },

  /* ========================= 逐题分析END =========================== */
    
    changeMonth() {
      if(!this.searchFormQsAnalysis.financialYear) {
        this.$message.error('请先选择年份');
        this.searchFormQsAnalysis.financialMonth = ''
        return false;
      }
    },

    handleSizeChangeLeft(val) {
      this.pageLeft.pageSize = val;
      this.initLeftData();
    },
    handleCurrentChangeLeft(val) {
      this.pageLeft.curPage = val;
      this.initLeftData();
    },
    handleSizeChangeBottom(val) {
      this.pageBottom.pageSize = val;
      this.initBottomData();
    },
    handleCurrentChangeBottom(val) {
      this.pageBottom.curPage = val;
      this.initBottomData();
    },
  },
  components: {
    adminTable,
  },
  props: ['questionType', 'isActiveEcharts']
}
</script>